<template>
    <div class="comment-page">
        <el-card class="card">
            <!-- 卡片头部：菜谱名称和创建时间 -->
            <template #header>
                <div class="page-header">
                    <h3>{{ foodData.cookbName }}</h3>
                    <p>{{ foodData.createTime }}</p>
                </div>
            </template>
            <!-- 卡片内容：菜谱信息、做法内容、评论表单和评论列表 -->
            <div class="page-content">
                <p class="info">{{ foodData.cuisine }} | {{ foodData.place }}</p>
                <div class="content-content">
                    <p>{{ foodData.content }}</p>
                </div>
                <!-- 评论表单 -->
                <el-form class="input-form">
                    <el-form-item>
                        <el-input v-model="inputValue" placeholder="请输入评论内容" class="my-input"
                            type="textarea"></el-input>
                    </el-form-item>
                    <el-form-item class="btn-item">
                        <el-button type="primary" @click="handleSubmit">提交评论</el-button>
                    </el-form-item>
                </el-form>
                <div class="comment-list">
                    <div v-for="(comment, index) in comments" :key="comment.commentId" class="comment-item">
                        <!-- 主评论 -->
                        <el-row :gutter="16" align="middle">
                            <!-- 头像（始终左侧固定） -->
                            <el-col :span="2" class="avatar-col">
                                <el-avatar :src="comment.userImg" size="small" shape="circle" class="main-avatar" />
                            </el-col>

                            <!-- 评论内容 -->
                            <el-col :span="22">
                                <div class="comment-main">
                                    <!-- 头部信息 -->
                                    <div class="comment-header">
                                        <div class="user-info">
                                            <span class="comment-username">{{ comment.userName }}</span>
                                            <span class="comment-time">{{ comment.createTime }}</span>
                                        </div>
                                        <el-button type="text" @click="reply(comment.commentId)" class="reply-btn">
                                            回复
                                        </el-button>
                                    </div>

                                    <!-- 评论内容 -->
                                    <div class="comment-content">
                                        {{ comment.content }}
                                    </div>

                                    <!-- 回复列表 -->
                                    <div v-if="getreplyForm.filter(r => r.commentId === comment.commentId).length"
                                        class="reply-list">
                                        <div v-for="reply in getreplyForm.filter(r => r.commentId === comment.commentId)"
                                            :key="reply.replyId" class="reply-item">
                                            <!-- 回复内容（无头像） -->
                                            <div class="reply-content">
                                                <div class="reply-header">
                                                    <span class="reply-username">{{ reply.userName }}</span>
                                                    <span class="reply-time">{{ reply.createTime }}</span>
                                                </div>
                                                <div class="reply-text">
                                                    {{ reply.content }}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </div>
        </el-card>
    </div>
    <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
        @on-close="onClose" @on-confirm="commit">

        <el-form :model="addreplyForm" ref="addFormRef">
            <!-- 菜谱名字 -->
            <el-form-item label="回复内容" prop="cookbName">
                <el-input v-model="addreplyForm.content" placeholder="请输入回复内容" />
            </el-form-item>
        </el-form>

    </Dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { useFoodStore } from '@/store/comment/index'
import { StatusType, type CommentTable } from '@/api/comment/commentModel'
import { useUserStore } from '@/store/islogin'
import { addCommentApi, getCommentApi } from '@/api/comment'
import { el } from 'element-plus/es/locales.mjs'
import Dialog from '../dialog/Dialog.vue'
import useDialog from '@/hooks/usedialog'
import http from '@/http'
import router from '@/router'
//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog()
//获取form表单组件实例
const addFormRef = ref<FormInstance>();
// 从全局 store 中获取菜谱数据（后端传来的数据）
const useFood = useFoodStore()
const foodData = useFood.getSelectedFood
//从store获取用户数据
const useUser = useUserStore()
// 表单输入数据
const inputValue = ref('')
//添加评论参数
const addCommentData = reactive({
    commentId: ' ',
    userId: ' ',
    cookbId: ' ',
    adminId: ' ',
    content: ' ',
    status: StatusType.Prohibit,
    createdTime: ' ',
    updatedTime: ' ',
    reviewedTime: ' '
})
//添加评论参数
const getCommentData = reactive({
    commentId: ' ',
    userId: ' ',
    cookbId: ' ',
    adminId: ' ',
    content: ' ',
    status: StatusType.Prohibit,
    createdTime: ' ',
    updatedTime: ' ',
    reviewedTime: ' '
})
//二级评论表单参数
const addreplyForm = reactive<Reply>({
    replyId: '',
    commentId: '',
    userId: '',
    content: '',
    createTime: '',
    userName: ''
});
interface Reply {
    replyId: string
    commentId: string
    userId: string
    content: string
    createTime: string
    userName: string
}
//接收参数数组
interface Comment {
    commentId: string;
    userName: string;
    userImg: string | null;
    content: string;
    createTime: string;
}
//二级评论查询参数
const getreplyForms = reactive<Reply>({
    replyId: '',
    commentId: '',
    userId: '',
    content: '',
    createTime: '',
    userName: ''
});
//定义获取后端传来的二级评论数据
const getreplyForm = ref<Reply[]>([]);
const comments = ref<Comment[]>([]);
//查询菜谱对应的评论
const getComment = async () => {
    if (useFood.getSelectedFood.cookbId) {
        getCommentData.cookbId = useFood.getSelectedFood.cookbId
        const res = await getCommentApi(getCommentData)
        if (res.code == 200) {
            comments.value = res.data
        }
    } else {
        ElMessage.error("请选择菜谱")
    }
}
//回复方法
const reply = (commentId: string) => {
    addreplyForm.commentId = commentId
    console.log(commentId)
    dialog.title = "回复用户"
    onShow()
}

// 提交评论，将新评论添加到评论列表中
const handleSubmit = async () => {
    if (inputValue.value.trim() === '') {
        ElMessage.error('评论内容不能为空')
        return
    }
    if (useFood.getSelectedFood.cookbId) {
        addCommentData.cookbId = useFood.getSelectedFood.cookbId
        if (useUser.user) {
            addCommentData.userId = useUser.user.userId
            addCommentData.content = inputValue.value
            const res = await addCommentApi(addCommentData)
            if (res.code == 200) {
                ElMessage.success("评论成功")
                getComment()
            }
        } else {
            ElMessage.error("请登录")
        }
    } else {
        ElMessage.error("请选择菜谱")
    }
}
const getTwoComment = async () => {
    const res = await getReplyApi(getreplyForms)
    if (res.code == 200) {
        getreplyForm.value = res.data;
    }

}
const addReplyApi = (parm: Reply) => {
    return http.post("/api/reply/add", parm)
}
const getReplyApi = (parm: Reply) => {
    return http.post("/api/reply/get", parm)
}
//二级评论输入内容
const commit = () => {
    //表单验证
    addFormRef.value?.validate(async (valid) => {
        if (valid) {
            if (useUser.user) {
                addreplyForm.userId = useUser.user.userId
            }
            const res = await addReplyApi(addreplyForm)
            if (res.code == 200) {
                getTwoComment()
                onClose()
                ElMessage.success(res.msg)
            }
        }
    });
}

//登录校验
function ensureLogin() {
  if (!useUser.user) {
    ElMessageBox.confirm(
      '未登录，请先登录',
      '提示',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        // 用户点击 “去登录”
        router.push('/login')
      })
      .catch(() => {
        // 用户点击 “取消” 或关闭对话框，不做任何处理
      })
  }
}
onMounted(() => {
    ensureLogin() 
    getComment()
    getTwoComment()
});

</script>

<style scoped>
/* 外层容器：占屏100%，居中显示 */
.comment-page {
    width: 100%;
    display: flex;
    justify-content: center;
    padding: 20px 0;
    background-color: #f7f7f7;
    box-sizing: border-box;
    overflow-y: auto;
}

/* 卡片样式：60%宽度，居中，增加阴影和圆角 */
.card {
    width: 60%;
    margin-top: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 页眉样式 */
.page-header {
    text-align: center;
    padding: 10px 0;
    border-bottom: 1px solid #ebeef5;
}

.page-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
}

.page-header p {
    margin: 0;
    font-size: 12px;
    color: #999;
}

/* 页内容整体内边距 */
.page-content {
    padding: 20px;
}
/* 主评论容器 */
.comment-item {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

/* 头像列固定宽度 */
.avatar-col {
  display: flex;
  justify-content: center;
}

/* 主评论内容区域 */
.comment-main {
  position: relative;
  padding-left: 12px;
}

/* 评论头部布局 */
.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.comment-username {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

/* 回复按钮样式 */
.reply-btn {
  padding: 0;
  height: auto;
  color: #666;
  &:hover {
    color: #409eff;
  }
}

/* 回复列表样式 */
.reply-list {
  margin-top: 16px;
  border-left: 2px solid #eee;
  padding-left: 24px;
}

.reply-item {
  margin: 12px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: background 0.3s;
  &:hover {
    background: #f1f3f5;
  }
}

.reply-header {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 4px;
}

.reply-username {
  font-weight: 500;
  font-size: 13px;
  color: #444;
}

.reply-time {
  font-size: 12px;
  color: #999;
}

.reply-text {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

/* 内容统一间距 */
.comment-content, .reply-text {
  padding: 8px 0;
}

/* 信息文字样式 */
.info {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
}

/* 做法内容区域 */
.content-content {
    min-height: 350px;
    background-color: #fff;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin-bottom: 20px;
    color: #333;
    line-height: 1.6;
}

/* 评论表单 */
.input-form {
    margin-bottom: 20px;
}

.btn-item {
    text-align: right;
}

/* 修改 Element Plus 输入框内部样式 */
.my-input .el-input__inner {
    height: 100px;
    padding: 10px;
    font-size: 14px;
}

/* 评论列表样式 */
.comment-list {
    border-top: 1px solid #ebeef5;
    padding-top: 15px;
    max-height: 400px;
    /* 设置最大高度，根据需要调整 */
    overflow-y: auto;
    /* 内容超出时出现垂直滚动条 */
}

.comment-item {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.avatar-col {
    display: flex;
    justify-content: center;
    align-items: center;
}

.comment-detail {
    display: flex;
    flex-direction: column;
}

.comment-header {
    margin-bottom: 5px;
}

.comment-username {
    font-weight: 600;
    margin-right: 10px;
    color: #333;
}

.comment-time {
    color: #999;
    font-size: 12px;
}

.comment-text {
    font-size: 14px;
    color: #555;
    line-height: 1.5;
}
</style>